package org.zh.svs.order.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.aopalliance.intercept.MethodInterceptor;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import org.zh.svs.pro.remote.ProRemote;

import javax.sql.DataSource;

import static org.zh.client.cache.RemoteCache.localCache;

@Configuration
public class OrderConfig {

    private final Environment env;

    public OrderConfig(Environment env) {
        this.env = env;
    }

    @Bean
    public WebFilter contextPathWebFilter() {
        return (ServerWebExchange exchange, WebFilterChain chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            String context_path = env.getProperty("server.servlet.context-path");
            if (context_path != null && request.getURI().getPath().startsWith(context_path)) {
                ServerHttpRequest newRequest = request.mutate()
                        .path(request.getURI().getPath().substring(context_path.length()))
                        .build();
                return chain.filter(exchange.mutate().request(newRequest).build());
            }
            return chain.filter(exchange);
        };
    }

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/family");
        dataSource.setUsername("zhou");
        dataSource.setPassword("zhouhang");
        return dataSource;
    }

    @Bean
    public ProRemote getProxy(MethodInterceptor methodInterceptor) {
        ProxyFactory pf = new ProxyFactory(ProRemote.class, methodInterceptor);
        localCache.getSubClass().add(ProRemote.class.getName());
        return (ProRemote) pf.getProxy();
    }
}
